package JDBC;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class selectSql {
    public static void main(String[] args) throws SQLException {
        //1创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/student?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("");
        //2建立连接
        Connection connection = dataSource.getConnection();
        //3构造sql
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        //4执行sql
        ResultSet resultSet = statement.executeQuery();
        //5遍历结果集
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = "+id+" name= "+name);
        }
        //6释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
